﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bikiball.Core
{
    public class BikiObject
    {
        private Dictionary<Type, Property> _properties = null;

        public BikiObject()
        {
            _properties = new Dictionary<Type, Property>();
        }

        public T GetProperties<T>() where T:Property
        {
            return (T)this._properties[typeof(T)];
        }

        public Property GetProperties(Type T)
        {
            return this._properties[T];
        }

        public void SetProperties<T>(T property) where T : Property
        {
            if (HasProperty<T>())
            {
                this._properties[typeof(T)] = property;
            }
            else
            {
                if (CheckDependency(property))
                {
                    PropInit(property);
                    this._properties.Add(typeof(T), property);
                }
            }       
        }

        private void PropInit(Property property)
        {
              foreach (Type type in property.Dependencies)
              {
                  property.PropInit(this.GetProperties(type));
              }
        }

        public bool HasProperty<T>() where T : Property
        {
            return this._properties.Any(x => x.Key.Name == typeof(T).Name);
        }

        #warning "Peut être optimisé"
        private bool CheckDependency(Property property)
        {
            bool dependency = true;
            foreach (Type type in property.Dependencies)
            {
                dependency &= this._properties.Any(x => x.Value.GetType().Name == type.Name);
            }
            return dependency;
        }
    }
}
